#include "LogFile.h"

namespace droneswarm
{
    LogFile::LogFile( std::string baseName, int flushEveryN )
        : baseName_( baseName )
        , flushEveryN_( flushEveryN )
        , count_( 0 )
        , mutex_( new monsoon::RWMutex )
    {
        file_.reset( new AppendFile( baseName ) );
    }

    LogFile::~LogFile() {}

    //将日志写入文件,这个方法是对AppendFile进行操作的封装
    void LogFile::append( const char *logline, int len )
    {
        //获取锁
        monsoon::RWMutex::WriteLock lock( *mutex_ );
        append_unlocked( logline, len );
    }

    //刷新缓冲区
    void LogFile::flush()
    {
        monsoon::RWMutex::WriteLock lock( *mutex_ );
        file_->flush();
    }

    void LogFile::append_unlocked( const char *logline, int len )
    {
        file_->append( logline, len );
        count_++;
        if ( count_ >= flushEveryN_ )
        {
            count_ = 0;
            file_->flush();
        }
    }
}  // namespace droneswarm